import React, { useState } from 'react';
import { Modal, Form, Input, Button, Tabs, message, Typography, Select, Row, Col } from 'antd';
import { UserOutlined, MailOutlined, LockOutlined, EyeInvisibleOutlined, EyeTwoTone, BookOutlined, TeamOutlined } from '@ant-design/icons';
import { useAuth } from '../store/AuthContext';
import { userService } from '../services/api';
import { INTEREST_OPTIONS } from '../constants/interests';

const { TabPane } = Tabs;
const { Title, Text } = Typography;
const { Option } = Select;

interface LoginModalProps {
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}

const LoginModal: React.FC<LoginModalProps> = ({ visible, onCancel, onSuccess }) => {
  const [loading, setLoading] = useState(false);
  const [codeLoading, setCodeLoading] = useState(false);
  const [countdown, setCountdown] = useState(0);
  const [isNewUser, setIsNewUser] = useState(false);
  const [userEmail, setUserEmail] = useState('');
  const [form] = Form.useForm();
  const [accountForm] = Form.useForm();
  const { login, loginWithCode, sendLoginCode, loginLoading } = useAuth();

  const handlePasswordLogin = async (values: { login: string; password: string }) => {
    if (loginLoading) return; // 防止重复提交
    try {
      console.log('开始密码登录:', values);
      const success = await login(values.login, values.password);
      console.log('登录结果:', success);
      if (success) {
        console.log('登录成功，调用onSuccess');
        onSuccess();
      } else {
        console.log('登录失败，不调用onSuccess');
      }
    } catch (error) {
      console.log('登录异常:', error);
      // 错误处理已在AuthContext中完成
    }
  };

  const handleCodeLogin = async (values: { email: string; code: string }) => {
    if (loginLoading) return; // 防止重复提交
    try {
      console.log('开始验证码登录:', values);
      const response = await loginWithCode(values.email, values.code) as any;
      console.log('登录响应:', response);
      
      if (response.success) {
        if (response.isNewUser) {
          // 新用户，进入注册流程
          console.log('检测到新用户，进入注册流程');
          setIsNewUser(true);
          setUserEmail(values.email);
          message.info('欢迎新用户！请完善您的信息');
        } else {
          // 老用户，直接登录成功
          console.log('老用户登录成功');
          onSuccess();
        }
      } else {
        console.log('登录失败');
        message.error('登录失败，请检查验证码');
      }
    } catch (error) {
      console.error('登录错误:', error);
      message.error('登录失败，请稍后重试');
    }
  };

  const handleSendCode = async () => {
    const email = form.getFieldValue('email');
    if (!email) {
      message.error('请先输入邮箱地址');
      return;
    }

    setCodeLoading(true);
    try {
      const success = await sendLoginCode(email);
      if (success) {
        message.success('验证码已发送到您的邮箱');
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown((prev) => {
            if (prev <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prev - 1;
          });
        }, 1000);
      } else {
        message.error('发送失败');
      }
    } finally {
      setCodeLoading(false);
    }
  };

  const handleAccountSubmit = async (values: any) => {
    setLoading(true);
    try {
      console.log('开始创建账号:', { email: userEmail, username: values.username });
      
      // 验证密码确认
      if (values.password !== values.confirmPassword) {
        message.error('两次输入的密码不一致');
        return;
      }

      // 创建用户账号
      const response = await userService.createAccount({
        email: userEmail,
        username: values.username,
        password: values.password
      });
      
      console.log('账号创建响应:', response);
      
      // 使用账号密码登录
      const loginResponse = await login(values.username, values.password);
      if (loginResponse) {
        // 登录成功后更新个人信息
        try {
          const profileData = {
            gender: values.gender,
            grade: values.grade,
            major: values.major,
            dream_career: values.dream_career,
            interests: values.interests
          };
          
          await userService.updateProfile(profileData);
          message.success('注册完成！欢迎使用LinkMate');
          onSuccess();
        } catch (profileError) {
          console.error('更新个人信息失败:', profileError);
          message.warning('账号创建成功，但个人信息更新失败，您可以在设置中完善');
          onSuccess();
        }
      } else {
        message.error('登录失败，请重试');
      }
    } catch (error: any) {
      console.error('创建账号错误:', error);
      message.error(error.message || '注册失败');
    } finally {
      setLoading(false);
    }
  };



  const renderAccountForm = () => (
    <div style={{ padding: '20px 0' }}>
      <div style={{ textAlign: 'center', marginBottom: 30 }}>
        <div style={{
          width: 60,
          height: 60,
          background: 'linear-gradient(135deg, #1890ff, #40a9ff)',
          borderRadius: '50%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          margin: '0 auto 20px',
          boxShadow: '0 4px 15px rgba(24, 144, 255, 0.3)'
        }}>
          <UserOutlined style={{ fontSize: '24px', color: 'white' }} />
        </div>
        <Title level={3} style={{ marginBottom: 8 }}>完善账号信息</Title>
        <Text type="secondary">请设置您的登录账号和密码，以及基本信息</Text>
      </div>

      <Form
        form={accountForm}
        layout="vertical"
        onFinish={handleAccountSubmit}
        autoComplete="off"
        initialValues={{
          gender: 'male',
          grade: '大一',
          major: '',
          dream_career: '',
          interests: []
        }}
      >
        <Form.Item
          name="username"
          label="账号"
          rules={[
            { required: true, message: '请输入账号' },
            { min: 3, message: '账号至少3个字符' },
            { max: 20, message: '账号最多20个字符' }
          ]}
        >
          <Input
            prefix={<UserOutlined style={{ color: '#1890ff' }} />}
            placeholder="请输入您的账号"
            size="large"
          />
        </Form.Item>

        <Form.Item
          name="password"
          label="密码"
          rules={[
            { required: true, message: '请输入密码' },
            { min: 6, message: '密码至少6个字符' }
          ]}
        >
          <Input.Password
            prefix={<LockOutlined style={{ color: '#1890ff' }} />}
            placeholder="请输入密码"
            size="large"
          />
        </Form.Item>

        <Form.Item
          name="confirmPassword"
          label="确认密码"
          rules={[
            { required: true, message: '请确认密码' },
            ({ getFieldValue }) => ({
              validator(_, value) {
                if (!value || getFieldValue('password') === value) {
                  return Promise.resolve();
                }
                return Promise.reject(new Error('两次输入的密码不一致'));
              },
            }),
          ]}
        >
          <Input.Password
            prefix={<LockOutlined style={{ color: '#1890ff' }} />}
            placeholder="请再次输入密码"
            size="large"
          />
        </Form.Item>

        <Row gutter={16}>
          <Col span={12}>
            <Form.Item
              name="gender"
              label="性别"
            >
              <Select placeholder="请选择性别" size="large">
                <Option value="male">男</Option>
                <Option value="female">女</Option>
                <Option value="other">其他</Option>
              </Select>
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              name="grade"
              label="年级"
            >
              <Select placeholder="请选择年级" size="large">
                <Option value="大一">大一</Option>
                <Option value="大二">大二</Option>
                <Option value="大三">大三</Option>
                <Option value="大四">大四</Option>
                <Option value="研一">研一</Option>
                <Option value="研二">研二</Option>
                <Option value="研三">研三</Option>
                <Option value="博士">博士</Option>
                <Option value="其他">其他</Option>
              </Select>
            </Form.Item>
          </Col>
        </Row>

        <Form.Item
          name="major"
          label="专业"
        >
          <Input
            prefix={<BookOutlined style={{ color: '#1890ff' }} />}
            placeholder="请输入您的专业"
            size="large"
          />
        </Form.Item>

        <Form.Item
          name="dream_career"
          label="理想职业"
        >
          <Input
            prefix={<TeamOutlined style={{ color: '#1890ff' }} />}
            placeholder="请输入您的理想职业"
            size="large"
          />
        </Form.Item>

        <Form.Item
          name="interests"
          label="兴趣爱好"
        >
          <Select
            mode="multiple"
            placeholder="请选择您的兴趣爱好"
            size="large"
            style={{ width: '100%' }}
          >
            {INTEREST_OPTIONS.map(interest => (
              <Option key={interest} value={interest}>{interest}</Option>
            ))}
          </Select>
        </Form.Item>

        <Form.Item style={{ marginBottom: 0, marginTop: 30 }}>
          <Button
            type="primary"
            htmlType="submit"
            loading={loginLoading}
            size="large"
            block
            style={{
              height: '50px',
              fontSize: '16px',
              fontWeight: 'bold',
              background: 'linear-gradient(135deg, #1890ff, #40a9ff)',
              border: 'none',
              borderRadius: '25px',
              boxShadow: '0 4px 15px rgba(24, 144, 255, 0.3)'
            }}
          >
            完成注册
          </Button>
        </Form.Item>
      </Form>
    </div>
  );


  const renderLoginForm = () => (
    <div style={{ padding: '20px 0' }}>
      <div style={{ textAlign: 'center', marginBottom: 30 }}>
        <div style={{
          width: 60,
          height: 60,
          background: 'linear-gradient(135deg, #1890ff, #40a9ff)',
          borderRadius: '50%',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          margin: '0 auto 20px',
          boxShadow: '0 4px 15px rgba(24, 144, 255, 0.3)'
        }}>
          <UserOutlined style={{ fontSize: '24px', color: 'white' }} />
        </div>
        <Title level={3} style={{ marginBottom: 8 }}>欢迎使用LinkMate</Title>
        <Text type="secondary">请选择登录方式</Text>
      </div>

      <Tabs defaultActiveKey="code" centered>
        <TabPane tab="验证码登录" key="code">
          <Form
            form={form}
            layout="vertical"
            onFinish={handleCodeLogin}
            autoComplete="off"
          >
            <Form.Item
              name="email"
              label="邮箱地址"
              rules={[
                { required: true, message: '请输入邮箱地址' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input
                prefix={<MailOutlined style={{ color: '#1890ff' }} />}
                placeholder="请输入您的邮箱地址"
                size="large"
              />
            </Form.Item>

            <Form.Item
              name="code"
              label="验证码"
              rules={[
                { required: true, message: '请输入验证码' },
                { len: 6, message: '验证码必须是6位数字' }
              ]}
            >
              <Input
                prefix={<LockOutlined style={{ color: '#1890ff' }} />}
                placeholder="请输入6位验证码"
                size="large"
                maxLength={6}
              />
            </Form.Item>

            <Form.Item style={{ marginBottom: 16 }}>
              <Button
                type="link"
                onClick={handleSendCode}
                loading={codeLoading}
                disabled={countdown > 0}
                style={{ padding: 0, color: '#1890ff' }}
              >
                {countdown > 0 ? `${countdown}秒后重新发送` : '获取验证码'}
              </Button>
            </Form.Item>

            <Form.Item style={{ marginBottom: 0 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={loginLoading}
                size="large"
                block
                style={{
                  height: '50px',
                  fontSize: '16px',
                  fontWeight: 'bold',
                  background: 'linear-gradient(135deg, #1890ff, #40a9ff)',
                  border: 'none',
                  borderRadius: '25px',
                  boxShadow: '0 4px 15px rgba(24, 144, 255, 0.3)'
                }}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </TabPane>

        <TabPane tab="账号密码登录" key="password">
          <Form
            layout="vertical"
            onFinish={handlePasswordLogin}
            autoComplete="off"
          >
            <Form.Item
              name="login"
              label="账号或邮箱"
              rules={[{ required: true, message: '请输入账号或邮箱' }]}
            >
              <Input
                prefix={<UserOutlined style={{ color: '#1890ff' }} />}
                placeholder="请输入账号或邮箱"
                size="large"
              />
            </Form.Item>

            <Form.Item
              name="password"
              label="密码"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password
                prefix={<LockOutlined style={{ color: '#1890ff' }} />}
                placeholder="请输入密码"
                size="large"
                iconRender={(visible) => (visible ? <EyeTwoTone /> : <EyeInvisibleOutlined />)}
              />
            </Form.Item>

            <Form.Item style={{ marginBottom: 0 }}>
              <Button
                type="primary"
                htmlType="submit"
                loading={loginLoading}
                size="large"
                block
                style={{
                  height: '50px',
                  fontSize: '16px',
                  fontWeight: 'bold',
                  background: 'linear-gradient(135deg, #1890ff, #40a9ff)',
                  border: 'none',
                  borderRadius: '25px',
                  boxShadow: '0 4px 15px rgba(24, 144, 255, 0.3)'
                }}
              >
                登录
              </Button>
            </Form.Item>
          </Form>
        </TabPane>
      </Tabs>
    </div>
  );

  return (
    <Modal
      title={null}
      open={visible}
      onCancel={onCancel}
      footer={null}
      width={600}
      centered
      style={{ borderRadius: '20px' }}
    >
      {isNewUser ? (
        renderAccountForm()
      ) : (
        renderLoginForm()
      )}
    </Modal>
  );
};

export default LoginModal;